package com.acmen.easyapi.validation.validator;

import com.acmen.easyapi.util.StringUtil;
import com.acmen.easyapi.validation.DataTypeValidator;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * In校验器
 *
 * @author acmen
 * @date 2022-04-06
 */
@Component
public class InValidator implements DataTypeValidator {
    private final static String PATTERN = "^in\\([\\s\\S]*(,[\\s\\S]*)*\\)";

    public boolean matches(String exp) {
        boolean isMatch = Pattern.matches(PATTERN, exp);
        return isMatch;
    }

    @Override
    public void validate(String exp, Object data, List<String> messages) {
        String exp2 = exp.trim();
        exp2 = exp2.substring("in(".length());
        exp2 = exp2.substring(0, exp2.length() - 1);
        String[] datas = exp2.split(",");
        for (String d : datas) {
            if (data instanceof Float) {
                Float f = Float.parseFloat(d);
                if (f == data) {
                    return;
                }
            } else if (d.equals(data.toString())) {
                return;
            }
        }
        messages.add("数据枚举" + exp.substring(2));
    }


    /**
     * 校验说明
     *
     * @return
     */
    @Override
    public String getNote(String exp) {
        if(StringUtil.isNotEmpty(exp)){
            String exp2 = exp.trim().substring(2);
            return "数据枚举"+exp2+"；";
        }
        return "in(a,b,c)：数据枚举(a,b,c)；";
    }
}
